import { useState, useEffect, useMemo } from "react";
import type { GetProp, TableProps } from "antd";
import type { SorterResult } from "antd/es/table/interface";
import type { AnyObject } from "antd/es/_util/type";
import type { SearchFormItem, ProTableColumns } from "./Index";
import dayjs from "dayjs";
// type ColumnsType<T extends object = object> = TableProps<T>['columns'];
type TablePaginationConfig = Exclude<GetProp<TableProps, "pagination">, boolean>;
// 表格参数类型
interface TableParams {
	pagination?: TablePaginationConfig;
	sortField?: SorterResult<any>["field"];
	sortOrder?: SorterResult<any>["order"];
	defaultFilters?: Parameters<GetProp<TableProps, "onChange">>[1];
}
// 将对象转换为 URL 参数
const toURLSearchParams = <T extends AnyObject>(record: T) => {
	const params = new URLSearchParams();
	for (const [key, value] of Object.entries(record)) {
		params.append(key, value);
	}
	return params;
};

// 获取表格参数
const getRandomuserParams = (params: TableParams, isPagination?: boolean) => {
	const { pagination, defaultFilters, sortField, sortOrder, ...restParams } = params;

	const result: Record<string, any> = {};

	// https://github.com/mockapi-io/docs/wiki/Code-examples#pagination
	// 如果开启分页，则添加分页参数
	if (isPagination) {
		result.limit = pagination?.pageSize;
		result.page = pagination?.current;
	}

	// https://github.com/mockapi-io/docs/wiki/Code-examples#filtering
	if (defaultFilters) {
		for (const [key, value] of Object.entries(defaultFilters)) {
			if (value !== undefined && value !== null) {
				result[key] = value;
			}
		}
	}

	// https://github.com/mockapi-io/docs/wiki/Code-examples#sorting
	if (sortField) {
		result.orderby = sortField;
		result.order = sortOrder === "ascend" ? "asc" : "desc";
	}

	// 处理其他参数
	for (const [key, value] of Object.entries(restParams)) {
		if (value !== undefined && value !== null) {
			result[key] = value;
		}
	}

	return result;
};
export const useTable = <T extends object = any, R = any>({
	api,
	rowSelection,
	isRowSelection,
	searchForm,
	columns,
	isPagination,
	dataSource,
}: {
	api?: (params?: any) => Promise<any>;
	rowSelection?: R;
	isRowSelection?: boolean;
	searchForm?: SearchFormItem[];
	columns?: ProTableColumns<T>;
	isPagination?: boolean;
	dataSource?: T[];
}) => {
	// 表格数据
	const [data, setData] = useState<T[]>();
	// 自定义表格列
	const [showSelectCustom, setShowSelectCustom] = useState<boolean>(false);
	// 加载状态
	const [loading, setLoading] = useState(false);
	// 选中行
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	// 自定义列
	const [columnsNew, setColumnsNew] = useState<ProTableColumns<T>>(columns);
	// 搜索参数
	const [searchParams, setSearchParams] = useState<any>({});
	// 表格参数
	const [tableParams, setTableParams] = useState<TableParams>({
		pagination: {
			current: 1,
			pageSize: 10,
		},
	});

	// 搜索表单
	const searchFormNew = useMemo(() => {
		return searchForm?.filter((item) => {
			return !item.hidden;
		});
	}, [searchForm]);

	// 设置初始值，并绑定到form，重置不清除掉值
	const defaultSearchParams = useMemo(() => {
		return searchFormNew?.reduce(
			(acc, item) => {
				// 如果存在范围，则将转化key和value的值
				if (item.rangeName) {
					acc[item.rangeName[0]] = item.initialValue[0]
						? dayjs(item.initialValue[0]).format(item.format as string)
						: "";
					acc[item.rangeName[1]] = item.initialValue[1]
						? dayjs(item.initialValue[1]).format(item.format as string)
						: "";
					// 删除原有的key
					delete acc[item.name];
				} else {
					acc[item.name] = item.initialValue;
				}
				return acc;
			},
			{} as Record<string, any>,
		);
	}, [searchFormNew]);

	// 获取数据
	const fetchData = (searchParams?: any) => {
		if (!api) {
			return;
		}
		const searchParamsNew = searchParams ?? {};
		// 获取参数
		const params = toURLSearchParams(
			getRandomuserParams({ ...defaultSearchParams, ...tableParams, ...searchParamsNew }, isPagination ?? true),
		);
		// 设置搜索参数
		setSearchParams(searchParamsNew);
		// 设置加载状态
		setLoading(true);
		// 请求数据

		api?.(params)
			.then((res) => {
				// 设置表格数据
				const list = res?.page?.list ?? [];
				const total = res?.page?.totalCount ?? 0;
				setData(list);
				// 设置加载状态
				setLoading(false);
				// 设置表格参数
				setTableParams({
					...tableParams,
					pagination: {
						...tableParams.pagination,
						total,
					},
				});
			})
			.catch(() => {
				setLoading(false);
			});
	};

	// 使用 useEffect 来处理数据请求
	useEffect(fetchData, [
		tableParams.pagination?.current,
		tableParams.pagination?.pageSize,
		tableParams?.sortOrder,
		tableParams?.sortField,
	]);

	// 使用 useEffect 来处理数据请求
	useEffect(() => {
		if (dataSource && dataSource.length > 0) {
			setData(dataSource);
		}
	}, [dataSource]);

	// 处理表格变化
	const handleTableChange: TableProps<T>["onChange"] = (pagination, defaultFilters, sorter) => {
		setTableParams({
			pagination,
			defaultFilters,
			sortOrder: Array.isArray(sorter) ? undefined : sorter.order,
			sortField: Array.isArray(sorter) ? undefined : sorter.field,
		});

		// `dataSource` is useless since `pageSize` changed
		if (pagination.pageSize !== tableParams.pagination?.pageSize) {
			setData([]);
		}
	};
	// 选中行
	const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
		console.log("selectedRowKeys changed: ", newSelectedRowKeys);
		setSelectedRowKeys(newSelectedRowKeys);
	};

	// 行选择, 默认不开启，如果开启则使用 rowSelection 的配置，否则使用默认配置
	const rowSelectionNew = isRowSelection
		? rowSelection ||
			({
				selectedRowKeys,
				onChange: onSelectChange,
			} as unknown as R)
		: undefined;

	// 自定义列后的回调函数
	const changeColumns = (columnKeys: React.Key[]) => {
		const columnsNew = columns?.filter((item) => {
			return columnKeys.includes(item.key as string);
		});
		setColumnsNew(columnsNew);
	};

	return {
		tableParams,
		setTableParams,
		data,
		loading,
		handleTableChange,
		rowSelectionNew,
		selectedRowKeys,
		fetchData,
		searchFormNew,
		searchParams,
		showSelectCustom,
		setShowSelectCustom,
		changeColumns,
		columnsNew,
	};
};
